(function(D){
    $(document).ready(function(){
	var relations = {},
	autocompleteList = [],
	addObject,
	makeItem;

	// L'identifiant de la page dont on cherche les relations est passé en paramètre de l'URL
	D.pageId = location.href.split( "?" )[ 1 ].split( "&" )[ 0 ].split( "=" )[ 1 ];
	
	// Le nom de l'utilisateur connecté est récupéré de l'application
	// Dinah qui a servi à ouvrir cette fenêtre (c'est-à-dire la page
	// pour le réordonnancement)
	D.userName = self.opener.DESANTI.userName;

	addObject = function(result, obj){
	    var index = result.vocabLabel.value + encodeURIComponent(":") + result.relationLabel.value,
	    autocompleteItem;

	    if(!relations[index]){
		relations[index] = [obj];
	    }else{
		relations[index].push(obj);
	    }

	    autocompleteItem = decodeURIComponent(index);
	    if(!autocompleteList.hasElem(autocompleteItem)){
		autocompleteList.push(autocompleteItem);
	    }
	}

	removeRelation = function(relation, obj, f){
	    D.request("removeRelation.txt",
		      {
			  subject: D.pageId,
			  relation: relation,
			  object: obj
		      }, function(){
			  D.request("removeRelation2.txt",
				    {
					subject: D.pageId,
					relation: relation,
					object: obj,
					timestamp: new Date().getTime(),
					user: D.userName
				    }, f, true);
		      }, true);
	}

	makeItem = function(item){
	    var objs = relations[encodeURIComponent(item)],
	    container, element, delBtn, controls, img, a,
	    makeDelBtnClick;

	    $(".container").remove();

	    for(var i=0; i<objs.length; i+=1){
		container = $('<div>');
		container.addClass('container');
		controls = $('<div>');
		controls.addClass('controls');
		delBtn = $('<button>');
		delBtn.button({ label: "supprimer" });
		controls.append(delBtn);
		element = $('<div>');
		element.addClass('element');
		makeDelBtnClick = function(i){
		    var relationId = objs[i].relationId,
		    objectId = objs[i].objectId,
		    obj = objs[i],
		    representation = container;
		    
		    delBtn.click(function(){
			removeRelation(relationId, objectId, function(){
			    objs.remElem(obj);
			    representation.remove();
			});
			return false;
		    });
		}
		switch(objs[i].type){
		case "page":
		    a = $('<a>');
		    a.attr('href', 'javascript:self.opener.DESANTI.openPage("' + objs[i].objectId + '");');
		    img = $('<img>');
		    img.attr('src', objs[i].thumbnail);
		    a.append(img);
		    element.append(a);
		    makeDelBtnClick(i);
		    break;
		case "collection":
		    a = $('<a>');
		    a.attr('href', 'javascript:self.opener.DESANTI.openPage("' + objs[i].firstPage + '");');
		    img = $('<img>');
		    img.attr('src', objs[i].thumbnail);
		    a.append(img);
		    element.append(a);
		    makeDelBtnClick(i);
		    break;
		case "interval":
		    element.html(decodeURIComponent(objs[i].intervalValue));
		    (function(){
			var intervalId = objs[i].intervalId,
			representation = container,
			obj = objs[i];
			
			delBtn.click(function(){
			    D.request("deleteInterval1.txt",
				      {
					  "intervalId": intervalId
				      }, function(){
					  D.request("deleteInterval2.txt",
						    {
							"intervalId": intervalId,
							"user": D.userName,
							"timestamp": new Date().getTime()
						    }, function(){
							objs.remElem(obj);
							representation.remove();
						    }, true
						   );
				      }, true
				     );
			});
		    })();
		    break;
		case "term":
		    element.html(decodeURIComponent(objs[i].objectLabel));
		    makeDelBtnClick(i);
		    break;
		}
		container.append(element);
		container.append(delBtn);
		$("#elements").append(container);
	    }
	}

	D.request("pageRelations.txt",
		  {
		      pageId: D.pageId
		  },
		  function(results){
		      var obj;

		      for(var i=0; i<results.length; i+=1){
			  obj = { 
			      objectId: results[i].object.value,
			      relationId: results[i].relation.value
			  };
			  if(results[i].thumbnailFirstPage){
			      obj.type = "collection";
			      obj.thumbnail = results[i].thumbnailFirstPage.value;
			      obj.firstPage = results[i].firstPage.value;
			  }else if(results[i].thumbnail){
			      obj.type = "page";
			      obj.thumbnail = results[i].thumbnail.value;
			  }else{
			      obj.type = "term";
			      obj.objectLabel = results[i].objectLabel.value;
			  }
			  addObject(results[i], obj);
		      }
		      D.request("pageIntervals.txt",
				{
				    pageId: D.pageId
				},
				function(results){
				    var text, start, end, intervalValue, obj;

				    if(results.length>0){
					text = decodeURIComponent(results[0].text.value);
				    }
				    for(var i=0; i<results.length; i+=1){
					start = parseInt(results[i].start.value);
					end = parseInt(results[i].end.value);
					intervalValue = text.slice(start - 1, end);
					obj = {
					    type: "interval",
					    intervalId: results[i].interval.value,
					    relationId: results[i].relation.value,
					    intervalValue: intervalValue
					};
					addObject(results[i], obj);
				    }
				    D.autocomplete(autocompleteList, 
						   document.getElementById("relationLabel"),
						   makeItem);
				});
		  });
    });
})(DESANTI);